package com.zyh.day04

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import java.sql.{Connection, DriverManager}

object Rdd2MySQLTest {
  def main(args: Array[String]): Unit = {
    val conf: SparkConf = new SparkConf()
      .setAppName("a")
      .setMaster("local[*]")
    val sc = new SparkContext(conf)
    val rdd1: RDD[String] = sc.makeRDD(List("hello", "baizhi", "hello", "world"), 2)
    rdd1.foreachPartition(it=>{
      Class.forName("com.mysql.jdbc.Driver")
      val username = "root"
      val password = "root"
      val url = "jdbc:mysql://hadoop10:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai"
      val conn: Connection = DriverManager.getConnection(url, username, password)
      val sql = "insert into spark_user values(null,?)"
      val ps = conn.prepareStatement(sql)
      it.foreach(data=>{
        ps.setString(1, data)
        ps.executeUpdate()
      })
      ps.close()
      conn.close()
    })
    sc.stop()
  }
}
